package com.yzf.wisecoder.wisecoderservice.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yzf.uidgeneratorcore.impl.CachedUidGenerator;
import com.yzf.wisecoder.wisecodercommon.exception.RRException;
import com.yzf.wisecoder.wisecodercommon.utils.SecurityUtils;
import com.yzf.wisecoder.wisecoderservice.service.ViewDbService;
import com.yzf.wisecoder.wisecoderstorage.mysql.dao.ViewDbDao;
import com.yzf.wisecoder.wisecoderstorage.mysql.entity.ViewDbEntity;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;


/**
 * @author jianghuiyong
 * @email jianghuiyong@yunzhangfang.com
 * @date 2020-05-12 10:20:48
 */
@Service("viewDbService")
@AllArgsConstructor
public class ViewDbServiceImpl extends ServiceImpl<ViewDbDao, ViewDbEntity> implements ViewDbService {

    private final CachedUidGenerator cachedUidGenerator;

    @Override
    public List<ViewDbEntity> queryList(Long projectId) {
        List<ViewDbEntity> list = list(new QueryWrapper<ViewDbEntity>().eq("project_id", projectId));
        return list;
    }

    @Override
    public boolean saveOrUpdateViewDb(ViewDbEntity viewDbEntity) {
        ViewDbEntity viewDbEntity1 = getOne(new QueryWrapper<ViewDbEntity>()
                .eq("db_name", viewDbEntity.getDbName())
                .eq("project_id", viewDbEntity.getProjectId()));
        if (viewDbEntity1 != null && (viewDbEntity == null
                || viewDbEntity.getDbId().longValue() != viewDbEntity1.getDbId().longValue())) {
            throw new RRException("数据源名称不能重复");
        }
        if (viewDbEntity.getDbId() == null) {
            viewDbEntity.setCreator(SecurityUtils.getUserId())
                    .setCreateTime(LocalDateTime.now())
                    .setDbId(cachedUidGenerator.getUID());
        }
        saveOrUpdate(viewDbEntity);
        return true;
    }

    @Override
    public boolean removeByProjectId(List<Long> projectIds) {
        if (CollectionUtil.isNotEmpty(projectIds)) {
            return remove(new QueryWrapper<ViewDbEntity>().in("project_id", projectIds));
        }
        return true;
    }

    @Override
    public List<ViewDbEntity> queryByDbIds(List<Long> dbIds) {
        return list(new QueryWrapper<ViewDbEntity>().in("db_id", dbIds));
    }
}